import { UserProfile } from './../../types/data.d'
import { ProfileEditResponse, UserResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

// type ResUser = {
//   message: string
//   data: User
// }
/**
 * 获取个人中心用户信息
 * @returns
 */
export const getUserAction = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 1. 获取当前登录人=》用户信息
    const res: UserResponse = await request.get('/user')
    console.log(res.data)
    // 2. 把用户信息存储到redux
    dispatch({ type: 'getUser/profile', payload: res.data })
  }
}
/**
 * 获取修改页面用户信息（数据回填）
 * @returns
 */
export const getEditUseAction = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 1. 获取修改的需要回填用户信息
    const { data }: ProfileEditResponse = await request.get('/user/profile')
    console.log('回填数据：', data)
    // 2. 存到redux
    dispatch({ type: 'getEditUser/profile', payload: data })
  }
}

// 修改个人信息
export const updateUserAction = (
  user: Partial<UserProfile>
): RootThunkAction => {
  return async (dispatch, getState) => {
    // 1.更新数据库
    await request.patch('/user/profile', user)
    // 2.更新redux=>局部更新
    dispatch({ type: 'update/profile', payload: user })
  }
}
